<?php

namespace common\models;

use Yii;
use yii\db\Exception;

/**
 * 项目附件（尽调9+1附件）
 * This is the model class for table "project_investigation_file".
 *
 * @property string $id
 * @property string $project_id
 * @property string $title
 * @property string $file_name
 * @property integer $category
 * @property string $size
 * @property integer $uploaded_by
 * @property integer $download_count
 * @property integer $state
 * @property string $created_at
 */
class ProjectInvestigationFile extends \yii\db\ActiveRecord
{
    const STATE_TRUE = 1; //是
    const STATE_FALSE = 2; //否

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'project_investigation_file';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['project_id', 'uploaded_by', 'title', 'file_name', 'size', 'category'], 'required'],
            [['project_id', 'category', 'uploaded_by', 'download_count', 'state'], 'integer'],
            [['created_at'], 'safe'],
            [['title', 'file_name', 'size',], 'string', 'max' => 255],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'project_id' => '项目',
            'title' => '文件名',
            'file_name' => '新文件名',
            'category' => '类别',
            'size' => '大小',
            'uploaded_by' => '上传人',
            'download_count' => '下载次数',
            'state' => '标注红旗',
            'created_at' => '创建时间',
        ];
    }

    /**
     * 新增多条数据
     * @param $uid 上传者
     * @param $project_id 项目id
     * @param $category 类别
     * @param $data 二维数组，一维元素中包含 文件大小、原文件名、新文件名
     */
    public function adds($uid, $project_id, $category, $data)
    {
        if (!empty($data) && is_array($data)) {
            $errorData = array();
            $transaction = Yii::$app->db->beginTransaction();
            try {
                foreach ($data as $value) {
                    $model = new ProjectInvestigationFile();
                    $model->project_id = $project_id;
                    $model->title = $value['olderFileName'];
                    $model->file_name = $value['fileName'];
                    $model->category = $category;
                    $model->size = $value['size'];
                    $model->uploaded_by = $uid;
                    $model->download_count = 0;
                    $model->state = 2;
                    $model->created_at = date('Y-m-d H:i:s', time());

                    if (!$model->save()) {
                        $errorData[] = [
                            'olderFileName' => $model->title,
                            'fileName' => $model->file_name
                        ];

                        $error = $model->getFirstErrors();
                        $msg = '';
                        if (!empty($error)) {
                            foreach ($error as $value) {
                                $msg .= $value;
                            }
                            $tmpStr = strip_tags($msg);
                            $tmpLen = mb_strlen($tmpStr);
                            $msg = mb_substr($tmpStr, 0, $tmpLen, 'utf-8');
                        }

                        //删除图片
                        //$path = UploadImgForm::PATH;
                        //$webroot = Yii::getAlias('@webroot');
                        //$file = $webroot . '/' . $path . $this->file_name;
                        //if (is_file($file)) {
                        //    if (!unlink($file)) {
                        //        throw new Exception("添加数据失败，删除图片{$this->title}失败");
                        //    }
                        //}
                        throw new Exception($msg);
                    } else {
                        $this->setUpdateLog($model->id, $model->project_id, $model, $uid, ProjectUpdateLog::MODULE_FILE, 1);
                    }
                }
                $transaction->commit();
                return array('state' => true, 'msg' => '上传成功', 'data' => $errorData);
            } catch (\Exception $e) {
                $msg = $e->getMessage();
                $transaction->rollBack();
                return array('state' => false, 'msg' => $msg, 'data' => $errorData);
            } catch (\Throwable $e) {
                $msg = $e->getMessage();
                $transaction->rollBack();
                return array('state' => false, 'msg' => $msg, 'data' => $errorData);
            }
        }
    }

    /**
     *  获取总条数
     * @param array $where 条件
     * @return int 条数
     */
    public function getCounts($where = array())
    {
        $count = (new \yii\db\Query())
            ->select([])
            ->from($this->tableName())
            ->where($where)
            ->count();

        return $count;
    }

    /**
     * 获取文件列表
     * @param array $where 条件
     * @param $limt 每页条数
     * @param $offset 起始下标
     * @return array 二维数组
     */
    public function getList($where = array(), $limt, $offset)
    {
        $list = (new \yii\db\Query())
            ->select([])
            ->from($this->tableName())
            ->where($where)
            ->limit($limt)
            ->offset($offset)
            ->orderBy(['state'=>SORT_ASC, 'id' => SORT_DESC])
            //->indexBy('id')
            ->all();

        $userModel = new UserModel();
        $userList = $userModel->getDepartmentUsersList();
        if (!empty($list)) {
            foreach ($list as $key => $value) {
                if (isset($userList[$value['uploaded_by']])) {
                    $list[$key]['uploaded_by'] = $userList[$value['uploaded_by']]['description'] . "-" . $userList[$value['uploaded_by']]['realname'];
                } else {
                    $list[$key]['uploaded_by'] = '';
                }
                $list[$key]['created_at'] = date('Y/m/d', strtotime($value['created_at']));
            }
        }

        return $list;
    }


    /**
     * @param $id 主键
     * @param $project_id 项目id
     * @param $changedAttributes 属性值
     * @param $userId 用户id
     * @param $module 项目修改日志module
     * @param $module_type 项目类型 1混合类，2抵押类
     * @param int $type 1为添加,2为修改，3为删除
     * @return array
     */
    public function setUpdateLog($id, $project_id, $changedAttributes, $userId, $module/*, $module_type*/, $type)
    {
        $model = self::findOne((int)$id);
        $project = Project::findOne($project_id);
        if ($model === null || $project === null) {
            return array('state' => false, 'msg' => '数据不存在');
        }

        if ($project->type != 2 ) {
            $project->type = 1;
        }

        $attributeLabels = $this->attributeLabels();
        $intAttributeLabels = ['project_id', 'category', 'uploaded_by', 'download_count', 'state'];
        $userInfo = (new UserModel())->getDepartmentUsersList();

        switch ($type) {
            //添加
            case 1:
                $data = $changedAttributes;
                if (!empty($data)) {
                    $log = '新增';
                    foreach ($data as $key => $value) {
                        if (in_array($key, $intAttributeLabels)) {
                            switch ($key) {
                                case 'project_id':
                                    $value = $project->title;
                                    break;
                                case 'category':
                                        $title = Yii::$app->params['InvestigationFileCategory'];
                                        $value = $title[(int)$value];
                                    break;
                                case 'uploaded_by':
                                    if ($value>0) {
                                        $value = $userInfo[$value]['description'] . '—' . $userInfo[$value]['realname'];
                                    } else {
                                        $value = '';
                                    }
                                    break;
                                case 'download_count':
                                    $value = $value .'次';
                                    break;
                                case 'state':
                                    switch ($value) {
                                        case 1:
                                            $value = '标注';
                                            break;
                                        case 2:
                                            $value = '未标注';
                                            break;
                                            $value = '';
                                        default:
                                    }
                                    break;
                                default:
                            }
                        }
                        if ($attributeLabels[$key] != 'ID') {
                            $log .= "{$attributeLabels[$key]}：{$value}\n";
                        }
                    }
                }
                break;

            //编辑
            case 2:
                //判断数据是否发生改变
                $state = false;
                $data = array(); //修改后的数据
                foreach ($changedAttributes as $key => $value) {
                    if ($model->$key != $value) {
                        $data[$key] = $value;
                        $state = true;
                    }
                }

                if (!$state) {
                    /*$model->lock_user = null;
                    $model->lock_timestamp = null;
                    if ($model->save()) {
                        return array('state' => true, 'msg' => '保存成功');
                    } else {
                        return array('state' => false, 'msg' => '保存失败');
                    }*/

                    return array('state' => true, 'msg' => '添加关键附件记录成功');
                }

                if (!empty($data)) {
                    $log = "【{$model->title}】";
                    //$log = '修改ID：' . $id . ',';
                    //$log = '修改ID为' . $id . '的立项信息数据,';
                    foreach ($data as $key => $value) {
                        if (in_array($key, $intAttributeLabels)) {
                            switch ($key) {
                                case 'project_id':
                                    $value = $project->title;
                                    break;
                                case 'category':
                                    $title = Yii::$app->params['InvestigationFileCategory'];
                                    $value = $title[(int)$value];
                                    break;
                                case 'uploaded_by':
                                    $value = '';
                                    if ($value>0 && isset($userInfo[$value])) {
                                        $value = $userInfo[$value]['description'] . '—' . $userInfo[$value]['realname'];
                                    }
                                    break;
                                case 'download_count':
                                    $value = $value .'次';
                                    break;
                                case 'state':
                                    switch ($value) {
                                        case 1:
                                            $value = '标注';
                                            break;
                                        case 2:
                                            $value = '未标注';
                                            break;
                                        default:
                                            $value = '';
                                    }
                                    break;
                                default:
                            }
                        }
                        $log .= "{$attributeLabels[$key]}：{$value}\n";
                    }
                }
                break;

            //删除
            case 3:
                //$log = "删除ID：{$id}，";
                $log = "删除记录【{$model->title}】，";
                break;
            default:
        }

        try {
            $time = date('Y-m-d H:i:s');
            $projectUpdateLog = new ProjectUpdateLog();
            if ($project->type !=2 ) {
                $project->type = 1;
            }
            $module_title_array = $projectUpdateLog->getModuleArrayTitle($project->type);
            $projectUpdateLog->project_id = $project_id;
            $projectUpdateLog->module = $module_title_array[$module];
            $projectUpdateLog->type = $project->type;
            $projectUpdateLog->created_at = $time;
            $projectUpdateLog->user_id = $userId;
            $projectUpdateLog->log = mb_substr($log, 0, -1, 'utf-8');
            $re1 = $projectUpdateLog->save();
            if (!$re1) {
                throw new \Exception('添加关键附件记录失败');
            }

            return array('state' => true, 'msg' => '添加关键附件记录成功');
        } catch (\Exception $e) {
            $message = $e->getMessage();
            return array('state' => false, 'msg' => $message);
        } catch (\Throwable $e) {
            $message = $e->getMessage();
            return array('state' => false, 'msg' => $message);
        }
    }

}
